package com.onepiece.shipelves.common.myutils.sort;

public class Bobble {

    static int niXu = 0;
    public static void main(String[] args) {
//        int[] nums = {3,7,1, 2, 3, 5, 2, 6, 9, 3, 2, 1};
        int[] nums = {3,2,1};
        int[] sortArray = sortArray(nums);
        System.out.println(niXu);
        for (int i = 0; i < sortArray.length; i++) {
            System.out.println(sortArray[i]);
        }
    }

    private static void swap(int[] nums, int i, int j) {
        niXu++;
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }

    //冒泡就是每次冒泡都可以把最大的数冒到最上面,所以每次从0位置冒到之前的最大泡泡下面就是length-i-1
    //交换的次数为逆序度，值为满有序度-有序度
    private static int[] sortArray(int[] nums) {
        int length = nums.length;
        for (int i = 0; i < length; i++) {

            boolean flag = false;
            for (int j = 0; j < length - i - 1; j++) {
                if(nums[j] > nums[j + 1]){
                    swap(nums, j+1, j);
                    flag = true;
                }
            }
            if(!flag){
                break;
            }
        }
        return nums;

    }
}
